<!-- 基础告警指标配置 -->
<template>
	<div class="container">
		<el-tabs v-model="unitType" @tab-click="handleClick">
			<el-tab-pane label="BPM" name="BPM"></el-tab-pane>
			<el-tab-pane label="NPM" name="NPM"></el-tab-pane>
		</el-tabs>

		<!-- 搜索条件 -->
		<yd-form class="yd-form-wraper" :model="formData" :options="formOptions">
			<template #form-btn>
				<el-button type="primary" icon="Search" @click="searchHandler">查 询</el-button>
			</template>
		</yd-form>

		<!--查询列表-->
		<YdTable
			:formData="formData"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			ref="multipleTable"
			@sizeChangeHandler="searchHandler"
			@currentChangeHandler="getData"
			@sortChangeHandler="getData"
		></YdTable>

		<!-- 添加或修改参数配置对话框 -->
		<el-dialog :title="title" v-model="open" width="800px" append-to-body center @close="cancel" :close-on-click-modal="false">
			<el-form ref="conForm" :model="form" label-width="100px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="指标名称:" prop="name">
							<el-input
								maxlength="50"
								v-model="form.name"
								placeholder="请输入指标名称"
								:disabled="true"
								style="width: 200px"
								:readonly="inputReadOnly"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="指标编码:" prop="code">
							<el-select v-model="form.code" placeholder="请选择" :disabled="true">
								<el-option v-for="dict in codeOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="指标单位:" prop="unit">
							<el-select v-model="form.unit" placeholder="请选择" :disabled="true">
								<el-option v-for="dict in unitOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="指标值类型:" prop="valueType">
							<el-select v-model="form.valueType" placeholder="请选择" :disabled="true">
								<el-option v-for="dict in typeOptions" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="指标说明:">
							<el-input
								maxlength="100"
								v-model="form.description"
								type="textarea"
								placeholder="请输入指标说明"
								rows="5"
								:disabled="inputReadOnly"
							></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer class="dialog-footer">
				<el-button type="primary" @click="submitForm" v-if="showSubmit">确 定</el-button>
				<el-button @click="cancel" v-if="showSubmit">取 消</el-button>
				<el-button type="primary" @click="cancel" v-if="showClose">关 闭</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="AlarmBaseIndicator" lang="tsx">
import { ref, reactive, toRefs, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import {
	queryBaseIndicatorsList,
	queryIndicatorById,
	editBaseIndicator,
	editBaseIndicatorsEnable,
	queryAlarmByIndicatorId,
} from '@/api/management/alarmManage/alarmIndicator';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { conforms } from 'lodash';

const { proxy } = useCurrentInstance();
const router = useRouter();

const statusOptions = ref([
	{ label: '是', value: 0 },
	{ label: '否', value: 1 },
]);
const unitType = ref('BPM');
const conForm = ref();

//是否显示确认提交按钮，查看详情的时候不需要确认按钮
const showSubmit = ref(true);
const showClose = ref(false);
const inputReadOnly = ref(false);
const unitOptions = ref<any[]>([]);
const codeOptions = ref<any[]>([]);
const typeOptions = ref<any[]>([]);
// 弹出层标题
const title = ref('');
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
// 是否显示弹出层
const open = ref(false);
// 搜索表单数据
let formData = reactive<FormModelType>({
	pageNum: 1,
	pageSize: 10,
	category: 'BPM',
});

// 表单项配置
const formOptions = ref<FormOptionType>([
	{
		type: 'select',
		label: '是否启用',
		prop: 'isEnable',
		placeholder: '请选择是否启用',
		isInitValue: false,
		children: [
			{ label: '是', value: 0 },
			{ label: '否', value: 1 },
		],
	},
	{
		type: 'input',
		label: '指标名称',
		prop: 'name',
		placeholder: '请输入指标名称',
	},
]);

// 列表配置
let tableConfig = reactive<TableConfigType>({
	columns: [
		{
			label: '指标名称',
			prop: 'name',
		},
		{
			label: '指标编码',
			prop: 'codeName',
		},
		{
			label: '指标值类型',
			prop: 'valueType',
			formatter(row, val) {
				if (val == 1) {
					return '数字';
				} else {
					return '字符';
				}
			},
		},
		{
			label: '指标单位',
			prop: 'unitName',
		},
		{
			label: '启用状态',
			prop: 'isEnable',
			render: (row, val) => {
				if (proxy.checkPermi(['monitor:basicAlarm:enable'])) {
					return (
						<el-switch
							v-model={row.isEnable}
							activeValue={0}
							inactiveValue={1}
							onChange={() => {
								console.log('oncahge--------');
								handleEnableChange(row);
							}}
						></el-switch>
					);
				}
				return <el-switch v-model={row.isEnable} disabled activeValue={0} inactiveValue={1}></el-switch>;
			},
		},
		{
			label: '操作',
			prop: '',
			width: 200,
			operation: [
				{
					text: '详情',
					handler: (scope) => getDetailHandle(scope.row),
				},
				{
					text: '修改',
					handler: (scope) => handleUpdate(scope.row),
					permi: ['monitor:basicAlarm:edit'],
				},
				{
					text: '告警',
					handler: (scope) => jumpToBaseAlarmHandle(scope.row),
					permi: ['monitor:basicAlarm:alarm'],
				},
			],
		},
	],
	// 开启复选框
	enableSelection: false,
	// 开启分页
	pagination: {
		pageNum: 1,
	},
	// 加载层
	loading: true,
});
// 列表数据
let tableData = reactive({
	data: [],
});

function handleClick(e: any) {
	console.log('e---', e);
	formData.category = e.paneName;
	tableData.data = [];
	tableConfig.pagination!.total = 0;
	getData();
}

function searchHandler() {
	tableConfig.pagination!.pageNum = 1;
	getData();
}
// 搜索
function getData() {
	tableConfig.loading = true;
	// formData.category = unitType.value;
	console.log('formData.category', formData.category);
	nextTick(() => {
		queryBaseIndicatorsList(formData).then((res: ApiResponse) => {
			if (res.code !== 0) {
				proxy.$modal.msgWarning(res.msg);
				tableConfig.loading = false;
				return;
			}
			tableConfig.loading = false;
			tableData.data = res.data.records;
			tableConfig.pagination!.total = res.data.total;
			tableData.data.forEach((item: any) => {
				if (item.isEnable === null) {
					item.isEnable = 1;
				}
			});
		});
	});
}
// 禁用启用
function handleEnableChange(row: any) {
	queryAlarmByIndicatorId(row.id).then((res: ApiResponse) => {
		if (res.code !== 0) {
			proxy.$modal.msgWarning(res.msg);
			return;
		}
		let dm = res.data;
		let dmStr = '';
		if (dm !== null && dm !== '') {
			dmStr = '禁用后这些告警都不再产生！：' + dm;
		}
		const data = {
			isEnable: row.isEnable,
			id: row.id,
		};
		//本来是启用状态，现在禁用
		if (row.isEnable == 1) {
			//在模版禁用时，需要查询m_alarms表里面是否有引用该模版，如果有需提示哪些告警引用到该模版，需解绑关系后才能禁用模版。
			let text = row.name;
			proxy.$modal
				.confirm('确认要禁用 ' + text + ' 吗?' + dmStr, '警告', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					cancelButtonClass: 'confirm-rigth-cancel-button',
					type: 'warning',
				})
				.then(function () {
					return editBaseIndicatorsEnable(data);
				})
				.then(() => {
					proxy.$modal.msgSuccess('禁用 ' + text + '成功');
				})
				.catch(function () {
					row.isEnable = row.isEnable === 0 ? 1 : 0;
				});
		} else {
			editBaseIndicatorsEnable(data).then((res) => {
				if (res.code !== 0) {
					proxy.$modal.msgWarning(res.msg);
					return;
				}
				proxy.$modal.msgSuccess('启用成功');
			});
		}
	});
}
/** 修改按钮操作 */
function handleUpdate(row: any) {
	reset();
	title.value = '修改基础告警指标';
	open.value = true;
	showSubmit.value = true;
	showClose.value = false;
	inputReadOnly.value = false;
	const id = row.id;
	if (id == null || id == '') {
		proxy.$modal.msgWarning('请选择要修改的统计告警指标。');
		return;
	}
	unitOptions.value = [];
	codeOptions.value = [];
	typeOptions.value = [];
	queryIndicatorById(id).then((res: ApiResponse) => {
		const data = res.data;
		//alert(JSON.stringify(res));
		let unitObj = {
			value: data.unit,
			label: data.unitName,
		};
		unitOptions.value.push(unitObj);
		let temp = {
			value: parseInt(data.codeId),
			label: data.code,
		};
		codeOptions.value.push(temp);
		let typeObj: anyObj = {};
		typeObj.value = data.valueType;
		if (data.valueType == 1) {
			typeObj.label = '数字类型';
		} else {
			typeObj.label = '字符类型';
		}
		typeOptions.value.push(typeObj);
		form.value = res.data;
	});
}
/** 提交按钮 */
function submitForm() {
	//新增或者修改提交前先校验表达式
	if (form.value.id != undefined) {
		editBaseIndicator(form.value).then((res) => {
			if (res.code === 0) {
				proxy.$modal.msgSuccess('修改成功');
				open.value = false;
				getData();
			} else {
				proxy.$modal.msgWarning(res.msg);
				return;
			}
		});
	}
}
// 取消按钮
function cancel() {
	open.value = false;
	reset();
}
// 表单重置
function reset() {
	form.value = {
		unitId: undefined,
		name: undefined,
		description: undefined,
		codeId: undefined,
		valueType: undefined,
	};
	conForm.value?.resetFields();
}

//点击跳转到基础告警页面
function jumpToBaseAlarmHandle(row: any) {
	router.push({
		path: '/management/alarmManage/baseAlarmConfig',
		query: {
			alarmIndicatorId: row.id,
		},
	});
}
//点击查看详情
function getDetailHandle(row: any) {
	reset();
	title.value = '基础告警指标配置详情';
	open.value = true;
	showSubmit.value = false;
	showClose.value = true;
	inputReadOnly.value = true;
	const id = row.id;
	unitOptions.value = [];
	codeOptions.value = [];
	typeOptions.value = [];
	queryIndicatorById(id).then((res: ApiResponse) => {
		const data = res.data;
		let unitObj = {
			value: data.unit,
			label: data.unitName,
		};
		unitOptions.value.push(unitObj);
		let temp = {
			value: parseInt(data.codeId),
			label: data.code,
		};
		codeOptions.value.push(temp);
		let typeObj: anyObj = {};
		typeObj.value = data.valueType;
		if (data.valueType == 1) {
			typeObj.label = '数字类型';
		} else {
			typeObj.label = '字符类型';
		}
		typeOptions.value.push(typeObj);
		form.value = res.data;
	});
}
getData();
</script>

<style lang="scss" scoped>
.container {
	margin: 10px;
}
</style>
